﻿namespace ChinaUnicom.Tasks
{
    using Avatar.Schedule;
    using System;
    using System.Net;

    public class AutologinTask : ITask
    {
        public AutologinTask()
        {
        }

        public void Start()
        {
            if (Started != null)
            {
                Started(this, EventArgs.Empty);
            }

            Factory.Operation.AutoLogin(s =>
            {
                if (s.Status == WebExceptionStatus.Success && s.Result.Contains(Context.Current.Account.Mobile))
                {
                    Authentication.Current.Signed = true;
                    Context.Current.Account.LastSigned = DateTime.Now;

                    if (Completed != null)
                    {
                        Completed(this, EventArgs.Empty);
                    }
                }
                else if (Failed != null)
                {
                    Failed(this, new FailedEventArgs(this, new Exception(Factory.Parser.Failed(s.Result))));
                }
            });
        }

        public int Delay { get { return 50; } }

        public bool IsUnique { get { return true; } }

        public event EventHandler Started;

        public event EventHandler Completed;

        public event EventHandler<FailedEventArgs> Failed;
    }
}
